package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-manager/cache"
	"novel-manager/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.Article{
		Title:   title,
		Content: content,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "article_" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*60)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
}
